/*
 * @Author: wfl
 * @LastEditors: wfl
 * @description: 
 * @updateInfo: 本次更新内容：
 * @Date: 2021-03-18 10:24:24
 * @LastEditTime: 2021-04-29 16:28:44
 */
import Axios, { CancelTokenSource } from 'axios'
import { Chunk } from '/@/utils/index'
import baseUrl from '/@/utils/index'
import { IRequest } from '/@/interface/if_rerquest'
const { CancelToken } = Axios;
let axiosList: CancelTokenSource[] = [];

interface FileStatus {
    fileExist: boolean;
    chunkList?: string[];
    desc: string;
}
// 切片数组转为FormData表单数据格式
export function uploadChunks(chunkList: Chunk[], fileName: string, cb: (percent: number) => void) {
    if (!Array.isArray(chunkList)) {
        throw (`chunkList is not a Array`);
        return
    }
    const requestList = chunkList.map((chunk: any): FormData => {
        let formData = new FormData();
        for (let i in chunk) {
            formData.append(i, chunk[i])
        }
        return formData
    })
    sendRequest(requestList, (percent: number) => {
        cb(percent)
    })
}

// 上传
export function sendRequest(chunkList: FormData[], cb: (percent: number) => void) {
    let len = chunkList.length;
    // 总数
    const uploadedTotal = len;
    // 已循环次数
    let sendCount = 0;
    // 已上传数量
    let uploadedCount = 0;
    while (len > 0 && sendCount <= uploadedTotal) {
        const source = CancelToken.source();
        const formData = chunkList[sendCount];
        sendCount++;
        len--;
        Axios({
            method: 'post',
            url: baseUrl.uploadChunkUrl,
            data: formData,
            headers: {
                'Content-Type': 'multipart/form-data'
            },
            cancelToken: source.token
        }).then(() => {
            uploadedCount++
            rmUploadedRequest(source);
            cb(Math.round((uploadedCount / uploadedTotal) * 100))
        })

        axiosList.push(source);
    }
}

export function handPauseUpload(){
    axiosList.forEach((item) => {
        item.cancel();
    });
    axiosList.length = 0;
}

function rmUploadedRequest(source: CancelTokenSource) {
    axiosList.forEach((item, index) => {
        if (item.token === source.token) {
            axiosList.splice(index, 1);
        }
    });
}